package com.lz.dsp.task.service.impl;

import com.lz.ad.common.generic.GenericMapper;
import com.lz.ad.common.generic.GenericServiceImpl;
import com.lz.ad.common.util.AppUtils;
import com.lz.dsp.task.common.Config;
import com.lz.dsp.task.dao.*;
import com.lz.dsp.task.entity.*;
import com.lz.dsp.task.enums.CreativeStatusEnum;
import com.lz.dsp.task.enums.EventTypeEnum;
import com.lz.dsp.task.service.OutdoorsStallService;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * 户外媒体档位
 *
 * @author zhy
 * @date 2019年7月13日
 */
@Service
@Log4j2
public class OutdoorsStallServiceImpl extends GenericServiceImpl<OutdoorsStall, Long> implements OutdoorsStallService {

    @Autowired
    private OutdoorsStallDao outdoorsStallDao;
    @Autowired
    private BdUploadFileDao bdUploadFileDao;
    @Autowired
    private MaterialAuditDetailDao materialAuditDetailDao;
    @Autowired
    private CompanyDao companyDao;
    @Autowired
    private CampaignDao campaignDao;

    @Override
    protected GenericMapper<OutdoorsStall, Long> getGenericMapper() {
        return outdoorsStallDao;
    }

    @Override
    public boolean handle(String uuid, Creative entity, EventTypeEnum eventTypeEnum, Map<String, Object> changeColumnMap) {

        //状态,0删除、1新增
        Integer status = null;

        if (EventTypeEnum.INSERT.equals(eventTypeEnum)) {
            //新增
            status = 1;
        } else if (EventTypeEnum.UPDATE.equals(eventTypeEnum)) {
            //修改
            if (changeColumnMap.containsKey(Config.COL_STATUS)) {
                if (CreativeStatusEnum.INVALID.eqValue(entity.getStatus())) {
                    //创意状态失效，表示逻辑删除
                    status = 0;
                } else if (CreativeStatusEnum.LZ_REVIEW.eqValue(entity.getStatus())) {
                    //系统审核，初始化审核明细表
                    //查询dsp企业信息
                    Map<String, Object> queryMap = new HashMap<>();
                    queryMap.put("dsp_user_id", entity.getCreate_user());
                    Company company = companyDao.selectOneByMap(queryMap);

                    queryMap.clear();
                    if (AppUtils.isNotEmpty(company)) {
                        queryMap.put("full_name", company.getFull_name());
                    }

                    queryMap.put("creative_no", entity.getId());
                    queryMap.put("dsp_user_id", entity.getCreate_user());
                    queryMap.put("dsp_user_name", entity.getCreate_user_name());
                    queryMap.put("status", CreativeStatusEnum.LZ_REVIEW.value());
                    queryMap.put("material_type", entity.getMaterial_type());
                    int result = materialAuditDetailDao.insertSelect(queryMap);
                    log.info("uuid={}, materialAuditDetail insertSelect result:{}", uuid, result);
                }
            }
        } else {
            //删除
            status = 0;
        }

        log.info("uuid={},option status-状态,0删除、1新增:{}", uuid, status);
        if (AppUtils.isNotEmpty(status)) {
            int result;

            //变更文件状态
            BdUploadFile bdUploadFile = new BdUploadFile();
            bdUploadFile.setFile_key(entity.getFile_key());
            bdUploadFile.setStatus(status);
            result = bdUploadFileDao.update(bdUploadFile);
            log.info("uuid={}, bdUploadFile update result:{}", uuid, result);

            if (status == 0) {
                //删除档位
                OutdoorsStall outdoorsStall = new OutdoorsStall();
                outdoorsStall.setUnit_no(entity.getUnit_no());
                outdoorsStall.setCreative_no(entity.getId());
                result = outdoorsStallDao.delete(outdoorsStall);
                log.info("uuid={}, utdoorsStall delete result:{}", uuid, result);
            } else if (status == 1) {
                //初始化档位
                Map<String, Object> queryMap = new HashMap<>();

                //查询是否已初始化
                queryMap.put("creative_no", entity.getId());
                queryMap.put("material_type", entity.getMaterial_type());
                long count = outdoorsStallDao.selectCountByMap(queryMap);
                if (count == 0) {
                    //查询推广计划
                    String campaign_no = entity.getCampaign_no();
                    queryMap.put("campaign_no", campaign_no);
                    Campaign campaign = campaignDao.selectOneByMap(queryMap);
                    if (AppUtils.isEmpty(campaign)) {
                        log.info("uuid={} 推广计划不存在", uuid);
                        return true;
                    }

                    //查询投放时段
                    queryMap.clear();
                    queryMap.put("campaign_no", campaign_no);
                    List<CampaignPutHours> put_hours = campaignDao.selectHourListByMap(queryMap);
                    if (AppUtils.isEmpty(put_hours)) {
                        log.info("uuid={} 投放时段为空", uuid);
                        return true;
                    }

                    Map<String, Object> hoursMap = new HashMap<>();
                    put_hours.forEach(campaignPutHours -> {
                        hoursMap.put(campaignPutHours.getWeek_name(), campaignPutHours.getHours());
                    });
                    log.info("uuid={} hoursMap={}", uuid,hoursMap);

                    String play_time = campaign.getPut_start_time();
                    String put_stop_time = campaign.getPut_stop_time();

                    while (play_time.compareTo(put_stop_time) <= 0) {
                        LocalDate datetime = LocalDate.parse(play_time);
                        //获取星期
                        String week_name = datetime.getDayOfWeek().toString().substring(0, 3);
                        Object hours = hoursMap.get(week_name);
                        if (AppUtils.isNotEmpty(hours)) {
                            log.info("uuid={} datetime={} hours={}",uuid,play_time,hours);
                            queryMap.clear();
                            queryMap.put("creative_no", entity.getId());
                            queryMap.put("play_time", play_time);
                            queryMap.put("hours", hours.toString());
                            result = outdoorsStallDao.insertSelect(queryMap);
                            log.info("uuid={}, play_time={} result={} utdoorsStall insertSelect result:{}", uuid, play_time, result);

                        }

                        play_time = datetime.plusDays(1).toString();
                    }

                } else {
                    log.info("uuid={}, creative_no={} 已初始化过档位", uuid, entity.getId());
                }

            }
        }

        return true;
    }
}
 